#include<stdio.h>
#include<windows.h>
#include<tlhelp32.h>
#include<time.h>
#include<io.h>

// 遍历所有进程信息
int rangeProcess(int f(PROCESSENTRY32 *lp))
{
  HANDLE h = CreateToolhelp32Snapshot(2, 0);
  if (h < 0) {
    return -1;
  }
  PROCESSENTRY32 lp;
  lp.dwSize = sizeof(lp);
  for (BOOL ok = Process32First(h, &lp); ok ; ok = Process32Next(h, &lp)) {
    int tmp = f(&lp);
    if (tmp != 0) {
      CloseHandle(h);
      return tmp;
    }
  }
  CloseHandle(h);
  return 0;
}

int main(int argc,char *argv[])
{
  if (access("D:\\print_info", F_OK)) {
    return 0; // 删除文件则不会打印信息
  }
  time_t timep = time(NULL);
  struct tm *p = gmtime(&timep);
  printf("[%d-%02d-%02d %02d:%02d:%02d] [",
    1900+p->tm_year,1+p->tm_mon,p->tm_mday,8+p->tm_hour,p->tm_min,p->tm_sec);
  for (int i = 0;i < argc; i++) {
    printf("%s ", argv[i]);
  }

  DWORD pid = GetCurrentProcessId();
  int parentProcessId(PROCESSENTRY32 *lp)
  {
    if (lp->th32ProcessID != pid) {
      return 0;
    }
    return lp->th32ParentProcessID;
  }
  DWORD ppid = rangeProcess(parentProcessId);
  printf("]\n%d -> ", ppid); // 得到父进程pid

  int parentProcessName(PROCESSENTRY32 *lp)
  {
    if (lp->th32ProcessID != ppid) {
      return 0;
    }
    printf("%s\n\n", lp->szExeFile);
    return -1; // 打印父进程名
  }
  rangeProcess(parentProcessName);
  system("pause");
	return 0;
}
